package ufpb.compiladores.lexico;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author seminick
 */
public class Reader {
    
    private BackableBufferedInputStream stream = null;
    private File inFile = null;
    private int apos = -1;
    
    public Reader(String path) throws IOException {
        
        this(new File(path));
    }
    
    public Reader(File path) throws IOException {
        
        inFile = path;
        this.stream = new BackableBufferedInputStream(new FileInputStream(inFile));
    }
    
    public boolean nextCharacter() {
        
        try {
        
            int ch = this.stream.read();
            if (ch != -1) {

                this.apos++;
                this.stream.setMarkPos(apos);
                return true;
            }
        } catch (IOException e) {
            
            return false;
        }
        
        return false;
    }
    
    public char getCurrentCharacter() {
        
        try {
        
            this.stream.reset();
            return (char) this.stream.read();
        } catch (IOException e) {}
        
        return '\0';
    }
    
    public boolean previousCharacter() {
        
        if (this.apos > 0) {
            
            this.apos--;
            this.stream.setMarkPos(apos);
            return true;
        }
        
        return false;
    }
    
    public boolean hasNextCharacter() {
        
        try {
            
            int ch = this.stream.read();
            if (ch != -1) {

                this.stream.setMarkPos(apos);
                return true;
            }
        } catch (IOException ioe) {}
        
        return false;
    }
    
    public boolean hasPreviousCharacter() {
        
        return this.apos > 0;
    }
    
    public void close() {
        
        try {
            
            this.stream.close();
        } catch (IOException ie) {
            
        }
    }
    
    private static class BackableBufferedInputStream extends BufferedInputStream {

        public BackableBufferedInputStream(InputStream in) {
            
            super(in);
        }

        public BackableBufferedInputStream(InputStream in, int i) {
            
            super(in, i);
        }
        
        public void setMarkPos(int pos) {
            
            this.markpos = pos;
        }
    }
}
